﻿using System;
using BoldBrick.Core.Logging;
using Microsoft.SharePoint;

namespace BoldBrick.SharePoint.CommonControls.Extensions
{
	/// <summary>
	/// Extension class for <see cref="SPContentType"/> objects
	/// </summary>
	public static class SPContentTypeEx
	{
		private static readonly ILogger log = Logger.GetLogger(typeof (SPContentTypeEx));

		/// <summary>
		/// Gets field link of content type by internal name
		/// </summary>
		/// <param name="contentType">The content type</param>
		/// <param name="internalName">Internal name of the field link</param>
		/// <returns>Returns field link of content type by internal name if there is one, otherwise returns null</returns>
		public static SPFieldLink GetFieldLink(this SPContentType contentType, string internalName)
		{
			try
			{
				SPFieldLink fieldLink = contentType.FieldLinks[internalName];
				return fieldLink;
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Error, ex, "'GetFieldLink' method failed.");
				return null;
			}
		}

		/// <summary>
		/// Adds field link into content type
		/// </summary>
		/// <param name="contentType">The content type</param>
		/// <param name="field">Source field of the field link</param>
		public static void AddFieldLink(this SPContentType contentType, SPField field)
		{
			SPFieldLink fieldLink = new SPFieldLink(field);
			contentType.FieldLinks.Add(fieldLink);
		}
	}
}
